// 1. 修改导入语句
import { ref, defineComponent, onMounted, watch } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { getDocumentList } from '@/api/document';
import { Loading, Search } from '@nutui/icons-vue';
import styles from './SearchPage.module.less';


// 注册PullRefresh组件
export default defineComponent({
  name: 'SearchPage',
 
  setup() {
    const searchText = ref('');
    // 状态管理
    const documentList = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalCount = ref(0);
    const error = ref('');
    
    // 使用 useRoute 获取路由对象
    const route = useRoute();
    const router = useRouter();

    // 从路由参数中获取 catalogId 和从 query 中获取 docInfo
    // 移除对 catalogId 的引用
    const docInfo = ref(route.query.docInfo || '');
    console.warn('docInfo = ', docInfo.value);
    
     const onSearch = () => {
       router.push(`/search?docInfo=${searchText.value}`);
    };
  
    // 获取文档列表数据
    const fetchDocumentList = async (page, size) => {
      loading.value = true;
      error.value = '';
      
      try {
        const parameter = {
          docInfo: docInfo.value || '药品', // 默认值为'药品'
          page: page || currentPage.value,
          limit: size || pageSize.value
        };
        
        console.warn('parameter = ', parameter);
        
        const response = await getDocumentList(parameter);
        
        if (response.data.code === 0) {
          documentList.value = response.data.data;
          totalCount.value = response.data.count;
        } else {
          // 接口返回失败
          documentList.value = [];
          totalCount.value = 0;
          error.value = '获取数据失败';
        }
      } catch (err) {
        documentList.value = [];
        totalCount.value = 0;
        error.value = '获取数据失败，请检查网络连接';
        console.error('获取文档列表失败:', err);
      } finally {
        loading.value = false;
      }
    };
    
    // 分页变化处理
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchDocumentList(page, pageSize.value);
    };
    
    // 页面大小变化处理
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1;
      fetchDocumentList(1, size);
    };
    
    // 处理文档点击事件
    const handleDocumentClick = (documentItem) => {
      if (documentItem.link_url) {
        // 去除链接中的空格
        const cleanUrl = documentItem.link_url.replace(/\s+/g, '');
        // 在新窗口打开链接
        window.open(cleanUrl, '_blank');
      }
    };
    
    // 获取状态样式
    const getStatusClass = (status) => {
      switch (status) {
        case '正式版':
          return styles.statusOfficial;
        case '征求意见':
          return styles.statusDraft;
        default:
          return styles.statusDefault;
      }
    };
    

    
    // 监听路由参数变化，更新数据
    // 移除对 route.params.catalogId 的监听
    watch(() => [route.query.docInfo], ([newDocInfo]) => {
      const hasChanged = newDocInfo !== docInfo.value;
      if (hasChanged) {
        // 移除对 newCatalogId 的处理
        // if (newCatalogId) catalogId.value = newCatalogId;
        if (newDocInfo) docInfo.value = newDocInfo;
        currentPage.value = 1; // 切换目录或搜索条件时重置为第一页
        fetchDocumentList(1, pageSize.value);
      }
    });
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchDocumentList();
    });
    
    // 在setup函数内部，其他函数定义之后添加这个函数
    
    // 高亮关键字函数
    const highlightKeyword = (text, keyword) => {
      console.warn('text = ', text);
      console.warn('keyword = ', keyword);
      if (!keyword || !text) {
        return text;
      }
      
      // 转义正则特殊字符
      const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const regex = new RegExp(`(${escapedKeyword})`, 'gi');
      const parts = text.split(regex);
      
      return (
        <>
          {parts.map((part, index) => 
            regex.test(part) ? 
            <span key={index} class={styles.highlightKeyword}>{part}</span> : 
            part
          )}
        </>
      );
    };
    
    // 然后修改文档内容的渲染部分
    return () => (
      <div class={styles.searchPage}>
        <div class={"navbar"}>
          <h3>关键字:{docInfo.value}</h3>
        </div>
        <div class={styles.searchContainer}>
          <nut-searchbar v-model={searchText.value} onSearch={onSearch} placeholder="法规检索">
            {{ 
              leftin: () => <Search class={styles.searchIcon} size="18" />,
              rightin: () =><span onClick={onSearch}>搜索</span>
            }}
          </nut-searchbar>
        </div>
        
          {/* 错误状态 */}
          {error.value && !loading.value && (
            <div class={styles.errorContainer}>
              <span>{error.value}</span>
              <button class={styles.retryButton} onClick={() => fetchDocumentList()}>
                重试
              </button>
            </div>
          )}
          
          {/* 列表内容 */}
          {!loading.value && documentList.value.length > 0 && (
            <div class={styles.listContainer}>
              {documentList.value.map((doc) => (
                <div 
                  key={doc.id} 
                  class={styles.documentItem} 
                  onClick={() => handleDocumentClick(doc)}
                >
                  <div class={styles.documentHeader}>
                    <h3 class={styles.documentTitle}>{highlightKeyword(doc.name, docInfo.value)}</h3>
                    <span class={`${styles.documentStatus} ${getStatusClass(doc.status)}`}>
                      {doc.status}
                    </span>
                  </div>
                  <div class={styles.documentContent}>
                    <p class={styles.documentContent}>{highlightKeyword(doc.content, docInfo.value)}</p>
                  </div>
                  <div class={styles.documentFooter}>
                    <span class={styles.releaseDate}>发布时间:{doc.release_date}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
          
          {/* 空状态 */}
          {!loading.value && documentList.value.length === 0 && (
            <div class={styles.emptyContainer}>
              <span>暂无数据</span>
            </div>
          )}
        {totalCount.value > 0 && !loading.value && (
          <div class={styles.paginationContainer}>
            <nut-pagination
              show-page-size="3"
              force-ellipses
              totalItems={totalCount.value}
              v-model={currentPage.value}
              onChange={handlePageChange}
              showInfo={true}
            />
          </div>
        )}
      </div>
    );
  }
});

